package com.dd.census.controller;

import com.dd.census.controller.common.BaseController;
import com.dd.census.entity.Parameter;
import com.dd.census.service.ParameterService;
import com.dd.census.tools.SysException;
import com.dd.census.tools.validator.ValidateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("rest/parameter")
public class ParameterController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ParameterController.class);

	@Autowired
	private ParameterService parameterService;

	@RequestMapping("selectPage")
	public ResponseEntity<Object> select(@RequestBody Parameter parameter, HttpServletRequest request) {
		try {
			// 基本输入验证
			ValidateUtil.validate(parameter);
			return this.doSuccess(request, parameterService.selectPage(parameter));

		} catch (SysException e) {
			// 业务异常
			return doFaild(request, e);

		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("selectAll")
	public ResponseEntity<Object> selectAll(@RequestBody Parameter parameter, HttpServletRequest request) {
		try {
			// 基本输入验证
			ValidateUtil.validate(parameter);

			return this.doSuccess(request, parameterService.selectList(parameter));

		} catch (SysException e) {
			// 业务异常
			return doFaild(request, e);

		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}


	@RequestMapping("insert")
	public ResponseEntity<Object> insert(HttpServletRequest request, @RequestBody List<Parameter> parameter) {

		try {
			// 基本输入验证
			ValidateUtil.validate(parameter);

			for(int i =0 ; i<parameter.size();i++){
				parameter.get(i).setCreateUserId(this.getUserId(request));
				parameter.get(i).setCreateTime(new Date());
			}

			int con = parameterService.insert(parameter);

			return this.doSuccess(request,con);
		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

}